package tingshu.servlet.Home;

import lombok.SneakyThrows;
import tingshu.util.DBUtil;
import tingshu.util.Log;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author houdaiqin
 * @date 2022/07/21 09:31
 **/
@WebServlet("/track")
public class TrackServlet extends HttpServlet {
    @Override
    @SneakyThrows
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        String type;
        InputStream content;

        try(Connection c= DBUtil.connection()){
            //根据tid获取该音频的类型和内容
            String sql="select type,content from tracks where tid=? order by tid";
            try(PreparedStatement ps=c.prepareStatement(sql)){
                ps.setString(1,tid);
                Log.println("执行SQL"+sql);
                try(ResultSet rs=ps.executeQuery()){
                    if (!rs.next()){
                        throw new RuntimeException("音频不存在");
                    }
                    type=rs.getString("type");
                    content=rs.getBinaryStream("content");
                }
            }
        }

        resp.setContentType(type);
        ServletOutputStream os= resp.getOutputStream();

        //将数据从 content(InputStream) 搬到os (OutputStream)
        byte[] buf=new byte[4096];
        while (true){
            int n=content.read(buf);
            if (n == -1){
                break;
            }
            os.write(buf,0,n);
        }
        os.flush();
        content.close();
    }
}